<template>
  <el-row class="webchat-fields">
    <el-col :span="24" class="b-info">
      <div :style="{height: fixed?'22px':'0px'}"></div>
      <header :class="[fixed, navMenuState ? 'navMenuState' : '']">
        <h3 class="font14"><span class="flow-name">{{flowObj.name}}</span><span class="flow-line"></span><span class="flow-name">{{businessTitle}}</span></h3>
        <div class="priority">
          <priority :business="detail"></priority>
        </div>
        <div class="timedown" >
          <el-tooltip placement="bottom" :openDelay="200" transition="fade-leave">
            <span class="font12 follow" @click.stop="setMyFollowed">
              <i class="follow-icon iconfont" :class="followed ? 'icon-yiguanzhu':'icon-guanzhu'"></i>
            </span>
            <div slot="content">
              {{$t('business.businessFollowed')}}
            </div>
          </el-tooltip>
          <!-- 催办 -->
          <el-tooltip placement="bottom" :openDelay="200" transition="fade-leave">
           <span class="font12 follow" :class="Cuiban ? 'cuibanStyle' : ''" @click.stop="businessCuiban" v-show="cuibanShow"  @mouseover="businessCuibanHover">
              <i class="follow-icon el-icon-bell" :class="Cuiban ? 'cuibanStyle' : ''"></i>
            </span>
            <div slot="content">
              {{cuibanContent}}
            </div>
          </el-tooltip>
          <el-tooltip placement="bottom" :openDelay="200" transition="fade-leave">
            <span  class="font12" @click.stop="changeBusinessMaster('me')" v-show="!detail.master&&masterSelect&&$store.state.session.user.type !=='admin'">
              <i class="iconfont icon-lingqu" data-v-7moor>
              </i>
            </span>
            <div slot="content">
              {{$t('business.received')}}
            </div>
          </el-tooltip>
        </div>
      </header>
      <main class="bus-info-main" id="business-info-form">
        <table>
          <tbody>
            <tr>
              <td class="name">{{$t('business.preAgent')}}</td>
              <td class="value">{{lastUpdateUser}}</td>
            </tr>
            <tr>
              <td class="name">{{$t('business.deal')}}</td>
              <td class="value">{{detail.lastUpdateTime}}</td>
            </tr>
            <tr>
              <td class="name">{{$t('business.master')}}</td>
              <td class="value">{{currentMaster}}</td>
            </tr>
          </tbody>
        </table>
        <div class="top-info"> </div>
        <el-row :gutter="20" v-for="item in items">
          <el-col v-for="col in item.cols" :span="24" class="padding-b">
            <div v-for="one in col.fields" :key="one._id">
              <b-input v-if="one.type==='single'"  :label="one.name" :default="one.default" :field="one" :id="one._id" :disabled="true"></b-input>
              <b-input v-if="one.type==='number'"  :label="one.name" :default="one.default" :id="one._id" :disabled="true"></b-input>
              <b-textarea v-if="one.type==='multi'"  :label="one.name" :default="one.default" :field="one" :id="one._id" :disabled="true"></b-textarea>
              <b-radio v-if="one.type==='radio'"  :label="one.name"  :dic="one.dic" :default="one.default" :id="one._id" :disabled="true" :field="one"></b-radio>
              <b-checkbox v-if="one.type==='checkbox'"  :label="one.name" :dic="one.dic" :default="one.default" :id="one._id" :disabled="true" :field="one"></b-checkbox>
              <b-datatime v-if="one.type==='date' || one.type==='datetime'" :type="one.type" :label="one.name"  :default="one.default" :id="one._id" :disabled="true"></b-datatime>
              <b-time v-if="one.type==='time'"  :label="one.name"  :default="one.default" :id="one._id" :disabled="true"></b-time>
              <b-select v-if="one.type==='dropdown' || one.type==='dropdownTree'" :type="one.type" :label="one.name" :dic="one.dic"  :default="one.default" :id="one._id" :disabled="true" :field="one"></b-select>
              <b-file v-if="one.type==='file'" :label="one.name" :default="one.default||[]" :id="one._id" @showBigImg="showBigImg" :disabled="true"></b-file>
            </div>
          </el-col>
        </el-row>
        <!--<el-row>-->
          <!--<el-col :span="24">-->
            <!--<el-form label-position='left'label-width="80px">-->
              <!--<el-form-item  :label="$t('business.master')" v-show="masterSelect">-->
                <!--<el-select size="mini" v-model.trim="master" :placeholder="$t('public.pleasePick')"  filterable @change="changeBusinessMaster" v-if="masterloading" style="width: 70%;">-->
                  <!--<el-option-->
                    <!--v-for="item in dealAgent"-->
                    <!--:label="item.label"-->
                    <!--:key="item.value"-->
                    <!--:value="item.value">-->
                  <!--</el-option>-->
                <!--</el-select>-->
              <!--</el-form-item>-->
            <!--</el-form>-->
          <!--</el-col>-->
        <!--</el-row>-->
        <el-row>
          <el-col :span="24">
            <span class="follow-label fl">{{$t('business.followedAgentsSetting')}}</span>
            <div class="follow-agent-wrap">
              <span class="follow-agent follow-common" v-for="item in folllowedAgents" :key="item._id">{{item.label}}<i class="el-icon-close" @click.stop="closeFollowedAgents(item._id)" v-show="masterSelect"></i></span>
              <el-popover
                ref="popover4"
                placement="bottom"
                @show="popoverShow"
                width="240"
                trigger="click">
                <agent-tree :readSeat="folllowedAgents" ref="agentTree" @saveFollowedAgents="saveFollowedAgents"></agent-tree>
              </el-popover>
              <span class="follow-agent-add follow-common"  v-show="masterSelect" v-popover:popover4><i class="el-icon-plus"></i> {{$t('public.add')}}</span>
            </div>
          </el-col>
        </el-row>
        <!-- 关联工单 -->
        <el-row>
          <el-col :span="24">
            <related-bussiness :relatedBusiness="relatedBusiness" :relatedBusinessShow="relatedBusinessShow" :masterSelect="masterSelect" @saveRelatedBusiness="saveRelatedBusiness" @closeRelatedBusiness="closeRelatedBusiness"></related-bussiness>
          </el-col>
        </el-row>
        <!-- 关联会话 -->
        <el-row>
          <el-col :span="24">
            <related-session :relatedWebchats="relatedWebchats" :relatedSessionShow="true" @saveRelatedSession="saveRelatedSession" @closeRelatedSession="closeRelatedSession" :masterSelect="masterSelect"></related-session>
          </el-col>
        </el-row>
        <!-- 关联通话 -->
        <el-row>
          <el-col :span="24">
            <related-call :relatedCallSheet="relatedCallSheet" :relatedCallShow="true" @saveRelatedCall="saveRelatedCall" @closeRelatedCall="closeRelatedCall" :masterSelect="masterSelect"></related-call>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form>
              <el-form-item class="fl">
                <el-select  v-show="masterSelect && !showChangeMaster" style="width: 92px" ref="master" size="mini" v-model.trim="master" :placeholder="$t('public.pleasePick')"  filterable @change="changeBusinessMaster" @visible-change="visiableChange">
                  <el-option
                    v-for="item in dealAgent"
                    :label="item.label"
                    :key="item.value"
                    :disabled="item.status=== 'disable'"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-button class="primary_btn" v-show="masterSelect && showChangeMaster && !forbidChange" @click="handleMaster">
                  {{$t('business.changeMaster1')}}
                </el-button>
              </el-form-item>
              <el-form-item class="wrapper fr" v-if="operatePane">
                <el-dropdown trigger="click" @command="showProcessBusinessTask" v-show="oprateSelect.length !== 1" size="small">
                  <el-button type="primary" class="primary_btn">
                    {{$t('business.beginDeal')}}<i class="el-icon-caret-bottom el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="item in oprateSelect" :command="item.value" :key="item.value">{{item.label}}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button type="primary" class="primary_btn" v-show="oprateSelect.length === 1" @click.stop="showProcessBusinessTask(oprateSelect[0].value)">
                  {{oprateSelect[0].label | lengthLimit}}
                </el-button>
                <!--<el-button type="info" class="ui-pass">-->
                <!--{{}}-->
                <!--</el-button>-->
                <el-button class="primary_btn ui-back" style="min-width: auto" type="warning" data-v-7moor @click.stop="businessBackShow" v-show="detail.businessFlag !== 'out' && allowBack">{{$t('business.return')}}</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </main>
    </el-col>
    <el-col :span="24" class="approval" v-if="approvalshow">
      <approval :process="processBusiness" :business="detail" v-on:event="businessEvent" flag="webchat"></approval>
    </el-col>
    <el-col :span="24">
      <business-back :business="detail" v-if="backShow" v-on:event="businessEvent" flag="webchat"></business-back>
    </el-col>
    <el-col :span="24" v-if="detail.rate">
      <business-rate :rate="detail.rate"></business-rate>
    </el-col>
    <el-col :span="24">
      <business-comment ref="businessComment" :business="detail" v-on:event="businessEvent" :isServiceBusiness="detail.businessFlag && detail.businessFlag === 'out'"></business-comment>
    </el-col>
    <el-dialog
      :title="$t('business.businessCuiBan')"
      :visible.sync="cuibanVisible"
      width="30%">
      <el-input
        type="textarea"
        :rows="5"
        :placeholder="$t('business.CuiBanTip')"
        v-model="cuiban" maxlength="500">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cuibanCancel" size="mini">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" size="mini" @click="cuibanSubmit">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>
<script>
  import Approval from '../Approval.vue'
  import BInput from '../base/Binput.vue'
  import BTextarea from '../base/Btextarea.vue'
  import BRadio from '../base/Bradio.vue'
  import BCheckbox from '../base/Bcheckbox.vue'
  import BDatatime from '../base/Bdatatime.vue'
  import BTime from '../base/Btime.vue'
  import BSelect from '../base/BselectDisable.vue'
  import BFile from '../base/Bfile.vue'
  import BusinessBack from '../businessBack.vue'
  import BusinessComment from '../businessComment.vue'
  import DetailTable from '../../call-detail/DetailTable.vue'
  import agentTree from '../agentTree.vue'
  import businessRate from '../businessRate'
  import priority from '../base/priority'
  import emailDetails from '@/components/business-modules/email/emailDetails.vue'
  import webChatView from '@/components/business-modules/webchat/webChatView.vue'
  import relatedBussiness from '../relatedBussiness.vue'
  import relatedSession from '../relatedSession.vue'
  import relatedCall from '../relatedCall.vue'
  import {getCache, deepClone, getCurrentDateTime, checkHideTel, isHasFunc} from '@/utils/m7Utils.js'
  import * as types from '@/store/modules/business/mutation-types.js'
  import { commitImgType2 } from '@/utils/publicMethod.js'
  import {busTimeDown, showCountDown, getRoleAgents, getFlowStepActionById, getFlowAction, arrayContainsStr, getFlowStepById, getFlowStepNameByCache, getObjectById, getStepRoles,getStepQueues,getQueueAgents} from '@/utils/workflowUtils.js'
  export default {
    name: 'BusinessInfo',
    props: {
      detail: Object,
      callScreen: {type: Boolean, default: false},
      showHistory: {type: Boolean, default: false},
      fixed: {type: String, default: ''},
      relatedBusinessShow: {type: Boolean, default: true},
      cacheId: {type: String, default: ''} // 缓存工单信息的id
    },
    components: {
      Approval,
      BInput,
      BTextarea,
      BRadio,
      BCheckbox,
      BDatatime,
      BTime,
      BSelect,
      BFile,
      BusinessBack,
      BusinessComment,
      DetailTable,
      agentTree,
      emailDetails,
      webChatView,
      businessRate,
      priority,
      relatedBussiness,
      relatedSession,
      relatedCall
    },
    data () {
      return {
        items: [
        ],
        master: '',
        followed: false,
        folllowedAgents: [],
        masterSelect: true,
        oprateSelect: [],
        dealAgent: [],
        operatePane: true,
        approvalshow: false,
        backShow: false,
        processBusiness: {},
        stepTimeColor: '',
        totalTimeColor: '',
        busTimeObj: {},
        stop: {stop: ''},
        masterloading: true,
        audioObj: {
          isShow: false,
          title: '',
          type: '',
          data: {}
        },
        priority: '1',
        flowObj: {},
        showChangeMaster: true,
        forbidChange:false,//是否禁止变更工单处理人
        allowBack:true,//是否可以退回工单
        cid:'',
        bussinessId:'',
        relatedBusiness:[],
        relatedWebchats:[],
        relatedCallSheet:[],
        cuiban:'',//催办内容
        cuibanShow: false, // 催办图标
        Cuiban: false, // 催办图标是否置灰
        cuibanContent:'催办', //催办提示
        cuibanVisible:false, // 催办
      }
    },
    computed: {
      businessTitle () {
        return getFlowStepNameByCache(this.detail.flow, this.detail.step)
      },
      stepExpireTimeDisplay () {
        if (this.busTimeObj.stepExpireTime < 0) {
          this.stepTimeColor = 'red'
        } else {
          this.stepTimeColor = ''
        }
        return showCountDown(this.busTimeObj.stepExpireTime || 0.1)
      },
      totalExpireTimeDisplay () {
        if (this.busTimeObj.totalExpireTime < 0) {
          this.totalTimeColor = 'red'
        } else {
          this.totalTimeColor = ''
        }
        return showCountDown(this.busTimeObj.totalExpireTime || 0.1)
      },
      lastUpdateUser () {
        let agentsAll = this.$agentsMap() || {}
        return agentsAll[this.detail.lastUpdateUser] ? agentsAll[this.detail.lastUpdateUser].displayName : ''
      },
      currentMaster () {
        let agentsAll = this.$agentsMap() || {}
        return agentsAll[this.master] ? agentsAll[this.master].displayName : this.$t('public.autoAssign')
      },
      navMenuState () {
        return this.$store.state.navMenuState || false
      }
    },
    filters: {
      lengthLimit (value) {
        if (value.length > 6) {
          return value.substring(0, 5) + '...'
        } else {
          return value
        }
      }
    },
    watch: {
      detail: {
        deep: true,
        handler: function () {
          // 防止工单刷新时发送changeMaster请求
          this.masterloading = false
          this.items = []
          this.approvalshow = false
          this.backShow = false
          this.$nextTick(() => {
            this.businessTransform()
          })
          let self = this
          busTimeDown(this.stop, this.detail, function (res) {
            self.busTimeObj = res
          })
          if (this.detail.status === 'complete' || this.detail.status === 'cancel') {
            clearInterval(this.stop.stop)
          }
        }
      }
    },
    methods: {
      //保存关联工单
      saveRelatedBusiness(searchContent){
        let businessDetail  = {}
        if(this.bussinessId){
          businessDetail = this.$store.state.business['current'].businessAction[this.bussinessId]
        }
        if(businessDetail.number && businessDetail.number == searchContent){
          this.$message.error(this.$t('business.businessTip1'))
        }else{
          if(!this.relatedBusiness.includes(searchContent)){
            let data = {_id: this.bussinessId, number:searchContent, operate:'add'}
            this.$store.dispatch('changeBusinessRelated', data).then((res) => {
              if (res.success) {
                this.relatedBusiness.push(searchContent)
                this.$message.success(this.$t('config.customer.addSucc'))
              } else {
                this.$message.success(this.$t('call.addLabelFail'))
              }
            })
          }else{
            this.$message.error(this.$t('business.businessTip2'))
          }
        }
      },
      //删除关联工单
      closeRelatedBusiness(number){
        let index = this.relatedBusiness.indexOf(number)
        this.relatedBusiness.splice(index,1)
        let data = {_id: this.detail._id, number, operate:'pull'}
        this.$store.dispatch('changeBusinessRelated', data).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('config.channel.deleteSuccess'))
          } else {
            this.$message.success(this.$t('config.channel.deleteFailure'))
          }
        })
      },
        //保存关联会话
      saveRelatedSession(searchContent){
         // 不能添加本身
        if(this.cacheId && this.cacheId === searchContent){
          this.$message.error(this.$t('business.businessTip8'))
        }else{
          //不可重复添加
          if(!this.relatedWebchats.includes(searchContent)){
            let data = {_id: this.bussinessId, number:searchContent, operate:'add'}
            this.$store.dispatch('changeBusinessRelated', data).then((res) => {
              if (res.success) {
                this.relatedWebchats.push(searchContent)
                this.$message.success(this.$t('config.customer.addSucc'))
              } else {
                this.$message.success(this.$t('call.addLabelFail'))
              }
            })
          }else{
            this.$message.error(this.$t('business.businessTip3'))
          }
        }
      },
      //删除关联会话
      closeRelatedSession(number){
        let index = this.relatedWebchats.indexOf(number)
        let data = {_id: this.detail._id, number, operate:'pull'}
        this.$store.dispatch('changeBusinessRelated', data).then((res) => {
          if (res.success) {
            this.relatedWebchats.splice(index,1)
            this.$message.success(this.$t('config.channel.deleteSuccess'))
          } else {
            this.$message.success(this.$t('config.channel.deleteFailure'))
          }
        })
      },
      // 保存关联通话
      saveRelatedCall(searchContent){
        //不可重复添加
        if(!this.relatedCallSheet.includes(searchContent)){
          let data = {_id: this.bussinessId, number:searchContent, operate:'add',type:'callSheet'}
          this.$store.dispatch('changeBusinessRelated', data).then((res) => {
            if (res.success) {
              this.relatedCallSheet.push(searchContent)
              this.$message.success(this.$t('config.customer.addSucc'))
            } else {
              this.$message.success(this.$t('call.addLabelFail'))
            }
          })
        }else{
          this.$message.error(this.$t('business.businessTip4'))
        }
      },
      // 删除关联通话
      closeRelatedCall(number){
        let index = this.relatedCallSheet.indexOf(number)
        let data = {_id: this.detail._id, number, operate:'pull',type:'callSheet'}
        this.$store.dispatch('changeBusinessRelated', data).then((res) => {
          if (res.success) {
            this.relatedCallSheet.splice(index,1)
            this.$message.success(this.$t('config.channel.deleteSuccess'))
          } else {
            this.$message.success(this.$t('config.channel.deleteFailure'))
          }
        })
      },
      showBigImg (data) {
        // 获取所有包含imgA的图片
        let _array = this.$el.querySelectorAll('.webchat-fields .imgA')
        commitImgType2(data, _array)
      },
      handleMaster () {
        // 变更处理人点击时打开下拉框
        this.showChangeMaster = false
        this.$nextTick(() => {
          if (this.$refs.master) {
            this.$refs.master.$el.querySelector('.el-input__icon').click((event) => {
              event.stopPropagation()
              return false
            })
          }
        })
      },
      visiableChange (value) {
        if (!value) {
          this.showChangeMaster = true
        }
      },
      businessEvent (data) {
        if (data.event === 'backAction') {
          this.backShow = false
        } else if (data.event === 'stepAction') {
          this.approvalshow = false
        } else if (data.event === 'commentAction') {
          let info = data.data || {}
          let form = info.form
          if(info.form.attach&&info.form.attach.length>0){
            info.form.existAttach = true
          }else{
            info.form.existAttach = false
          }
          if (info.isService && info.action === 'out') {
            if (!form.backInfo) {
              this.$message.error(this.$t('business.replyRequire'))
              return
            }
            form = Object.assign({history_type: 'reply'}, form)
            this.$store.dispatch('addConfigBusinessBackInfo', form).then(() => {
              let data = {
                'businessId': this.detail._id,
                'step': this.detail.step,
                'action': 'configBusiness',
                'history_type': 'reply',
                'excuteData': {
                  'backInfo': form.backInfo,
                  'attach': form.attach || []
                },
                'time': getCurrentDateTime(),
                'master': this.$store.state.session.user._id
              }
              this.$refs.businessComment.cancel()
              this.$store.commit(types.ADD_BUSINESS_ACTION_HISTORY, {data})
              // 备注成功后清楚缓存
              let busCache = this.$getCache('busCache')
              if (busCache[this.detail._id + 'commentIn']) {
                delete busCache[this.detail._id + 'commentIn']
              }
            })
          } else {
            if (!form.backInfo) {
              this.$message.error(this.$t('business.commentRequire'))
              return
            }
            this.$store.dispatch('addBusinessBackInfo', form).then(() => {
              let data = {
                'businessId': this.detail._id,
                'step': this.detail.step,
                'action': 'comment',
                'excuteData': {
                  'backInfo': form.backInfo,
                  'attach': form.attach || []
                },
                'time': getCurrentDateTime(),
                'master': this.$store.state.session.user._id
              }
              this.$refs.businessComment.cancel()
              this.$store.commit(types.ADD_BUSINESS_ACTION_HISTORY, {data})
              // 备注成功后清楚缓存
              let busCache = this.$getCache('busCache')
              if (busCache[this.detail._id + 'commentIn']) {
                delete busCache[this.detail._id + 'commentIn']
              }
            })
          }
        }
        this.$emit('event', data)
      },
      closeBack () {
        this.backShow = false
      },
      followedAgentsShow () {
        let agents = this.detail.followedAgents || []
        let agentsAll = this.$agentsMap() || {}
        this.followed = false
        this.folllowedAgents = agents.map((item) => {
          if (item === this.$store.state.session.sessionId) {
            this.followed = true
          }
          let agent = agentsAll[item] || {}
          return {_id: item, label: agent.displayName}
        })
      },
      async businessTransform () {
        this.relatedBusiness = this.detail.relatedBusiness || []
        this.relatedWebchats = this.detail.relatedWebchats || []
        this.relatedCallSheet = this.detail.relatedCallSheet || []
        this.bussinessId = this.detail._id
        if(isHasFunc('func_not_allow_change_business_master',this.$store.state.session.user)){
          //查询当前是否禁止变更工单处理人
          this.forbidChange = true;
        } 
        this.checkLastAction()
        this.priority = this.detail.priority ? this.detail.priority : '1'
        this.followedAgentsShow()
        let flow = getCache('businessFlow', this.detail.flow)
        let step = getFlowStepById(flow, this.detail.step)
        if (flow) {
          this.flowObj = flow
        }
        // 工单非完成或者取消状态下&&是创建人的情况下展示催办//工单模板配置催办间隔展示
        if(this.detail.createUser === this.$store.state.session.user._id && (this.detail.status !== "complete"|| this.detail.status !== "cancel")&& flow.urgeTime) {
          this.cuibanShow = true
        } else {
          this.cuibanShow = false
        }
        if(this.detail.master === this.detail.createUser){ // 当当前处理人等于创建人时不展示
          this.cuibanShow = false
        }
        // 没有当前处理人的时候催办按钮置灰
        if(this.detail.master) {
          this.Cuiban = false
          this.cuibanContent = this.$t('business.CuiBan')
          if(this.detail.urgeTime){ 
            this.cuibanFun()
          }
        } else {
          this.Cuiban = true
          this.cuibanContent = this.$t('business.CuiBanTip1')
        }
        // 定义客户字段顺序
        this.items = deepClone(step && step.stepFields ? step.stepFields : [])
        // 客户字段，定义内容样式
        let flowFields = flow ? flow.fields : []
        for (let i = 0; i < this.items.length; i++) {
          let row = this.items[i]
          for (let j = 0; j < row.cols.length; j++) {
            let col = row.cols[j]
            for (let k = 0; k < col.fields.length; k++) {
              let field = col.fields[k]
              let cacheField = getObjectById(flowFields, field._id)
              if (cacheField.type === 'dropdown' || cacheField.type === 'dropdownTree') {
                let value = this.detail[cacheField._id + '_default'] || ''
                let value1 = this.detail[cacheField._id + '_1_default'] || ''
                let value2 = this.detail[cacheField._id + '_2_default'] || ''
                let value3 = this.detail[cacheField._id + '_3_default'] || ''
                let value4 = this.detail[cacheField._id + '_4_default'] || ''
                let data = [value, value1, value2, value3, value4]
                cacheField['default'] = data
              } else if (cacheField.type === 'checkbox') {
                cacheField['default'] = this.detail[cacheField._id] !== '' ? this.detail[cacheField._id] : [cacheField['default']]
              } else {
                cacheField['default'] = this.detail[cacheField._id] !== '' ? this.detail[cacheField._id] : cacheField['default']
              }
              Object.assign(field, cacheField)
            }
          }
        }
        if (this.detail.status === 'complete' || (this.detail.status && this.detail.status === 'cancel')) { // 已完成状态
          this.operatePane = false
          this.masterSelect = false
        } else {
          let step = getCache('businessFlowStep', this.detail.step)
          let actions = step && step.actions ? step.actions : []
          console.log(actions,'actios')
          this.oprateSelect = []
          let flag = 0
          let role = []
          let queueOrRole = []
          let businessRole = []
          // mixedBizScope
          role = deepClone(this.$store.state.session.user.role)
          queueOrRole = deepClone(this.$store.state.session.user.mixedBizScope) // 新增的代表当前坐席角色或者技能组
          // 如果 工单的createUser是当前座席，该座席有工单创建人角色
          if (this.$store.state.session.sessionId === this.detail.createUser) {
            role.push('busCreateUser')
          }
          for (let i = 0; i < actions.length; i++) {
            var actionsItem = actions[i]
            if(actionsItem.actionAllow === 0) {
              if (arrayContainsStr(role, actionsItem.actionRole)) {
                flag++
                //兼容老数据，之前是字符串
                if(!Array.isArray(actionsItem.actionRole)){
                  actionsItem.actionRole = [actionsItem.actionRole]
                }
                actionsItem.actionRole.forEach(item=>{
                  businessRole.push(item)
                })
                this.oprateSelect.push({value: actionsItem._id, label: actionsItem.name})
              }
            } else {
              if (arrayContainsStr(queueOrRole, actionsItem.actionQueue)) {
                flag++
                //兼容老数据，之前是字符串
                actionsItem.actionQueue.forEach(item=>{
                  businessRole.push(item)
                })
                this.oprateSelect.push({value: actionsItem._id, label: actionsItem.name})
              }
            }
          }
//          role.pop()
          if (flag === 0 || (this.detail.master && this.detail.master !== this.$store.state.session.user._id)) {
            this.operatePane = false
          } else {
            this.operatePane = true
          }
          if (flag === 0) {
            this.masterSelect = false
            // 只有工单创建人角色
          } else if (flag === 1 && businessRole[0] === 'busCreateUser' && this.detail.createUser !== this.$store.state.session.sessionId) {
            this.masterSelect = false
          } else {
            this.masterSelect = true
          }
          if (flag === 1) {
          }
          let roles = getStepRoles(this.detail.step)   
          let queues = getStepQueues(this.detail.step)
          let roleAgentList = []
          let queueAgentList = []
          roleAgentList = getRoleAgents(roles, false, this.detail.createUser)
          queueAgentList = await getQueueAgents(queues, false)
          let agents = [...new Set(roleAgentList.concat(queueAgentList))]
          this.dealAgent = []
          if (agents.length !== 1) {
            this.dealAgent.push({label: this.$t('public.autoAssign'), value: ''})
          }
          this.master = this.detail.master
          this.masterloading = true
          for (let i = 0; i < agents.length; i++) {
            this.dealAgent.push({label: agents[i].displayName, value: agents[i]._id, status: agents[i].status})
          }
        }
      },
       checkLastAction(){
         if(this.detail.history&&this.detail.history.length>0){
          //在工单历史中查找action字段值是transformIn，并且历史中step和详情中的step相等的动作,就是上一步流转过来的动作详情，excuteAction就是上一步的动作id
          let fromData = this.detail.history.find(item=>{
            return item.action == "transformIn" && item.step == this.detail.step
          });
          let lastActionId = fromData.excuteAction 
          let fromStepId = fromData.fromStep;
           //根据上一步的步骤id(fromStepId)，查找上一步所有动作
          let flow = getCache('businessFlowStep',fromStepId );
          let actionArr = flow.actions;
          console.log(actionArr,'上一步所有动作');
          console.log(lastActionId,'上一步动作id');
          //在所有动作中确定上一步动作的具体数据
          let lastActionStep = actionArr.filter(item=>{
            return item._id == lastActionId
          })
          if(lastActionStep.length){
            if(lastActionStep[0].backFlag == "Y" || !lastActionStep[0].backFlag ){
              //兼容老数据，老数据没有backFlag字段，也可以退回工单
              this.allowBack = true
            }else if(lastActionStep[0].backFlag == "N"){
              this.allowBack = false
            }
          }
        }
      },
      showProcessBusinessTask (key) {
        let business = this.detail
        let actionId = key
        let stepId = business.step
        let action = getFlowAction(stepId, actionId)
        let nextStepId = action.jumpTo
        let nextStep = getCache('businessFlowStep', nextStepId)
        if (nextStep.type === 'sys') { // 如果是系统步骤，并且没有配置界面，则直接执行。
          let step = getCache('businessFlowStep', stepId)
          action = getFlowStepActionById(step.actions, actionId)
          let fields = action.actionFields
          if (fields.length === 0) {
            let executeData = {_id: business._id, actionId: actionId, master: 'sys'}
            let self = this
            this.$emit('event', {event: 'stepAction', data: {_id: this.detail._id, customer: this.detail.customer, form: executeData}})
            self.backShow = false
//            this.$store.dispatch('excuteBusinessStepAction', executeData).then((res) => {
//              self.backShow = false
//            })
            return
          }
        }
        this.processBusiness = {flow: business.flow, stepId: stepId, actionId: actionId, _id: business._id, master: this.master}
        this.approvalshow = true
        this.backShow = false
      },
      businessBackShow () {
        this.approvalshow = false
        if (this.backShow) {
          this.backShow = false
        } else {
          this.backShow = true
        }
      },
      changeBusinessMaster (value) {
        let self = this
        let master = value
        if (value === 'me') {
          master = this.$store.state.session.user._id
        }
        this.$store.dispatch('changeBusinessMaster', {_id: this.detail._id, master: master}).then((rep) => {
          if (!rep.success) {
            return
          }
          this.$message.success(this.$t('business.changeMasterSuccess'))
          if (master !== self.$store.state.session.user._id && master !== '') {
            self.operatePane = false
          } else {
            self.operatePane = true
          }
          self.approvalshow = false
          self.backShow = false
          this.showChangeMaster = true
          this.$emit('event', {event: 'changeBusinessMaster', data: {_id: this.detail._id, customer: this.detail.customer}})
          let data = {
            'businessId': self.detail._id,
            'step': self.detail.step,
            'action': 'assign',
            'excuteData': {
              'master': master
            },
            'time': getCurrentDateTime(),
            'master': self.$store.state.session.user._id
          }
          self.$store.commit(types.ADD_BUSINESS_ACTION_HISTORY, {data})
          self.$store.commit(types.CHANGE_BUSINESS_MASTER, {_id: this.detail._id, master: master})
        })
      },
      listen (flag) {
        this.audioObj.isShow = true
        this.audioObj.type = flag
        if (flag === 'call') {
          this.audioObj.title = this.$t('business.ListenToTheRecording2')
          this.$store.dispatch('relocationCustomerAtTable', {_id: this.detail.callId, self: this}).then((resp) => {
            if (resp) {
              this.audioObj.data = resp
            } else {
              this.audioObj.isShow = false
            }
          })
        } else if (flag === 'webchat') {
          this.audioObj.data = {}
          this.audioObj.data._id = this.detail.linkWebchat
          this.audioObj.title = this.$t('webchat.sessionRecord')
        } else if (flag === 'mail') {
          this.audioObj.title = this.$t('email.emailDetail')
          this.$store.dispatch('getLastEmail', {sessionId: this.detail.linkMail}).then(() => {
            this.audioObj.data = this.$store.state.email.lastEmail
          })
        }
      },
      popoverShow () {
        this.$refs.agentTree.setCheckedKeys()
      },
      saveFollowedAgents (agents) {
        if (agents.length === 0 && this.folllowedAgents.length === 0) {
          this.$message.error(this.$t('business.pleaseAddFollowedAgents'))
          return
        }
        this.followedSetting(agents)
      },
      closeFollowedAgents (agent) {
        let agents = this.detail.followedAgents.filter((item) => item !== agent)
        this.followedSetting(agents)
      },
      followedSetting (agents, type) {
        let data = {_id: this.detail._id, agents: agents}
//        let message = ''
        if (type === 'follow') {
          data.type = 'follow'
        } else if (type === 'unfollow') {
          data.type = 'unfollow'
        }
        return this.$store.dispatch('setFollowedAgents', data).then((res) => {
          if (res.success) {
            data.master = this.$store.state.session.sessionId
            data.step = this.detail.step
            this.$store.commit('business/FOLLOWED_SETTING', data)
            if (data.type === 'unfollow') {
              this.$message.success(this.$t('business.deleteFollowedAgents'))
            } else if (data.type === 'follow') {
              this.$message.success(this.$t('business.addFollowedAgents'))
            } else {
              this.$message.success(this.$t('business.changefollowedAgentSuc'))
            }
            return true
          } else {
            return false
          }
        })
      },
      setMyFollowed () {
        let agents = this.$store.state.session.sessionId
        if (this.followed) {
          this.followedSetting(agents, 'unfollow').then((res) => {
            if (res) {
              this.followed = false
            }
          })
        } else {
          this.followedSetting(agents, 'follow').then((res) => {
            if (res) {
              this.followed = true
            }
          })
        }
      },
      offAudio () {
        let play = document.getElementById('quality-autoplay_' + this.audioObj.data._id)
        if (play) {
          play.pause()
        }
      },
      checkHideTel (num) {
        return checkHideTel(num, this.$store.state.session.user)
      },
      // 催办
      businessCuiban(){
        if(!this.Cuiban){
          this.cuibanVisible = true
        }
      },
      businessCuibanHover(){
        this.cuibanFun()
      },
      // 催办确认
      async cuibanSubmit(){
        if (!this.cuiban) {
          this.$message.error(this.$t('business.CuiBanTip'))
        } else {
          let data = {
            _id: this.detail._id,
            urgeContent: this.cuiban
          }
          let data1 = { _id: this.detail._id,}
          await this.$store.dispatch('addUrgeContent',data).then(res=>{
            if(res && res.success) {
              data.master = this.$store.state.session.sessionId
              data.step = this.detail.step
              data.urgeTime = res.urgeTime
              this.$store.commit('business/CUIBAN', data)
              this.$message.success(this.$t('business.CuiBanSuccess'))
              this.cuibanVisible = false
              this.cuiban = ''              
            } else {
               this.$message.error(this.$t('business.CuiBanError'))
               this.cuibanVisible = false
            }
          })
        }
      },
      // 催办取消
      cuibanCancel(){
        this.cuibanVisible = false
      },
      // 催办间隔处理
      cuibanFun(flag,urge){
        let urgeTime = this.detail.urgeTime
        if(urgeTime) {
          console.log(urgeTime,'urgeTime')
          let date1 = (new Date().getTime()) / 1000;//计算当前时间戳 
          let date2 = urgeTime / 1000; //催办后的的时间戳 （字符串转时间戳）
          let date3 =  (date2- date1)*1000; //时间差的毫秒数
          //计算出相差天数
          let days = Math.floor(date3 / (24 * 3600 * 1000));
          //计算出小时数
          let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
          let hours = Math.floor(leave1 / (3600 * 1000));
          //计算相差分钟数
          let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
          let minutes = Math.floor(leave2 / (60 * 1000));
          //计算相差秒数
          let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
          let seconds = Math.round(leave3 / 1000);
          let newTime = ''
          if (date3 > 0) {
            console.log(days,hours,minutes,seconds,'days')
            this.Cuiban = true
              newTime = (days ? days + this.$t('public.day2') : '') + (hours ? hours + this.$t('public.hours2') : '') +  (minutes ? minutes + this.$t('configLazyLoad.qualityCheck.score') : '') + (seconds ? seconds + this.$t('public.seconds') : '')
          } else {
            this.Cuiban = false
          }
          // 时间到了之后催办可以点击
          setTimeout(()=>{
            this.Cuiban = false
          },date3)
          this.cuibanContent = this.$t('business.CuiBanTip2',{newTime})
        }
      }
    },
    beforeMount () {
      this.businessTransform()
      let self = this
      busTimeDown(this.stop, this.detail, function (res) {
        self.busTimeObj = res
      })
    },
    beforeDestroy () {
      clearInterval(this.stop.stop)
    },
    mounted () {
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../../assets/common.styl'
  .webchat-fields
    padding 15px 20px
  .b-info
    header
      display flex
      flex-direction row
      justify-content space-between
      h3
        color $cf-gray0
        font-weight bold
        .tittle-service
          color $c-pink
      .priority
        flex-grow 1
        padding-left 15px  
      .flow-name
        display inline-block
        max-width 85px
        text-overflow ellipsis
        overflow hidden
        white-space  nowrap
    header.header-fixed
      position fixed
      top 170px
      right 0
      z-index 9
      padding 12px 0
      width calc(100% - 397px)
      background #fff
      padding 12px 35px
      box-sizing border-box
      border-bottom 1px solid $c-border1
    header.header-fixed.navMenuState
      width calc(100% - 456px)
    .name
      max-width 72px
      color $cf-gray3
      font-size 12px
      padding-right 20px
    .value
      color $cf-gray1
      font-size 12px
      max-width 130px
      text-overflow ellipsis
      overflow hidden
      white-space nowrap
    main
      padding-top 20px
      .reason
        height 50px
      .log
        color $cf-gray1
        font-size 12px
        line-height 34px
        .bus-dealuser
          padding-left 2px
          box-sizing border-box
          max-width 70px
          text-overflow ellipsis
          overflow hidden
          white-space nowrap
      .line
        margin-bottom 15px
        &:before
          content ''
          height 1px
          width 100%
          display block
          border-top  1px dashed $cf-level2
      &:before
        content ''
        clear both
      .wrapper
        float right
        .ui-back
          margin-left 10px
  .business-processing
    padding-top 15px
  .timedown
    color $cf-level2
    .time
      color $cf-gray4
      cursor auto
      i
        color #b6b6b6
    .listen-icon
      margin-right 5px
      border 1px solid
      border-radius 50%
      font-size 12px
      text-indent 5px
    .follow
      color $cf-gray1
      cursor pointer
    .follow-icon
      color $c-main
      margin-right 5px
      font-size 16px
      text-indent 4px
    &>span
      display inline-block
      padding-left 10px
      float left
      color $cf-gray1
      cursor pointer
      .red
        color $c-pink
      i
        margin-right 5px
        font-size 16px
        line-height 20px
        display inline-block
        color $c-main
  .flow-line
    display inline-block
    border-top 1px solid $cf-gray1
    width 10px
    margin 0 5px
    padding-bottom 8px
  .deal-time
    padding 0 5px
  .follow-label
    line-height 24px
    font-size 12px
  .follow-agent-wrap
    padding-left 72px
    .follow-common
      float left
      position relative
      line-height 24px
      margin 0 0 10px 10px
      padding 0 10px
      border-radius 4px
    .follow-agent-add
      color $c-main
      border 1px solid $c-main
      cursor pointer
    .follow-agent
      line-height 26px
      background-color $c-bus-label
      color #fff
      &:hover
        .el-icon-close
          display block
      .el-icon-close
        display none
        position absolute
        right -10px
        top -10px
        width 24px
        height 24px
        font-size 16px
        line-height 24px
        transform scale(0.6)
        text-align center
        color #fff
        background-color $c-pink
        border-radius 50%
        border 1px solid #fff
        cursor pointer
  .detail-table-wrap
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    background rgba(0,0,0,.5)
    z-index 200
  .approval
    padding-top 20px
  .top-info
    padding-bottom 16px
    margin-bottom 16px
    border-bottom 1px solid $c-border1
.cuibanStyle 
  color #cbcbcb !important
</style>
